﻿using System.Threading.Tasks;
using MailService.Application.Contract;
using MailService.Domain.Aggregate.Mail;
using MailService.Domain.Repository;
using Microsoft.Extensions.Logging;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Domain.Entities.Events;
using Volo.Abp.EventBus;

namespace MailService.Application.EventHandler
{
    /// <summary>
    /// 邮件信息持久化事件处理程序
    /// </summary>
    public class MailPersistedEventHandler : ILocalEventHandler<EntityCreatedEventData<Mail>>, ITransientDependency
    {
        private readonly IMailManager _mailManager;
        private readonly IMailRepository _mailRepository;
        private readonly ILogger<MailPersistedEventHandler> _logger;
        
        public MailPersistedEventHandler(
            IMailManager mailManager,
            IMailRepository mailRepository,
            ILogger<MailPersistedEventHandler> logger)
        {
            _mailManager = mailManager;
            _mailRepository = mailRepository;
            _logger = logger;
        }
        
        /// <summary>
        /// 处理邮件发送
        /// </summary>
        public async Task HandleEventAsync(EntityCreatedEventData<Mail> eventData)
        {
            // 发送邮件并获取错误信息
            var exception = await _mailManager.SendMailWithTemplateAsync(
                MailResourceTemplateDefinitionProvider.MAIL_TEMPLATE_CONFIRM_MAIL,
                eventData.Entity.Receiver, eventData.Entity.Subject,
                () => new
                {
                    user = eventData.Entity.ExtraProperties["user"],
                    verify = eventData.Entity.ExtraProperties["verify"]
                });

            // 获取当前邮件存根
            var mail = eventData.Entity;
            mail.ExtraProperties.Clear();

            if (exception != null)
            {
                _logger.LogError($"发送给用户：{mail.UserId} 的邮件发送失败，错误原因：{exception.Message}");
                mail.Failed(exception.Message);
            }
            else
            {
                _logger.LogInformation($"发送给用户：{mail.UserId} 的邮件发送已发送");
                mail.HasSent();
            }

            await _mailRepository.UpdateAsync(mail);
        }
    }
}